package com.maori.languageapp.usermanager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.maori.languageapp.R;
import com.maori.languageapp.usermanager.Languageapp_Register_New_User.UploadTask;

public class Languageapp_Reset_User_Pass extends Activity{
	Button submituserregister,canceluserregister;
	EditText etenteremail,etnewuserpass,etcnewuserpass;
	ProgressDialog mProgressDialog;
	HttpParams httpParameters = new BasicHttpParams();
	int timeoutConnection = 5000;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	int EmailValidate = 0;
	LinearLayout dmresetreqemail;
	LinearLayout dmresetnewpassword;
	JSONArray jsonarray;
	ArrayList<HashMap<String, String>> arraylist;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// setContentView(R.layout.maori_login);
		setContentView(R.layout.languageapp_reset_user_pass);
		
		submituserregister = (Button) findViewById(R.id.submitbtn);
		canceluserregister = (Button) findViewById(R.id.cancelbtn);
		etenteremail = (EditText) findViewById(R.id.etenteremail);
		etnewuserpass = (EditText) findViewById(R.id.etnewuserpass);
		etcnewuserpass = (EditText) findViewById(R.id.etcnewuserpass);
		dmresetreqemail = (LinearLayout) findViewById(R.id.dmresetreqemail);
		dmresetnewpassword = (LinearLayout) findViewById(R.id.dmresetnewpassword);
		
		
		canceluserregister.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				onBackPressed();
			}
		});
		
		
		submituserregister.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				
				if(EmailValidate == 0){
					if (isNetworkAvailable()) {
						new ValidateUserEmail().execute();
					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Languageapp_Reset_User_Pass.this);
						b.setMessage("Internet connectivity failure.Try again!");
						b.show();
					}
				}
				
				else if(EmailValidate == 1){
					if(etnewuserpass.getText().toString().length()!=0 && etcnewuserpass.getText().toString().length()!=0){
						String passEnter1 = etnewuserpass.getText().toString();
						String passEnter2 = etcnewuserpass.getText().toString();
						if(passEnter1.equals(passEnter2)){
							new ValidateUserEmailPassword().execute();
						}
						
						else{
							final AlertDialog alertDialog = new AlertDialog.Builder(
									Languageapp_Reset_User_Pass.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("PASSWORD MISMATCH");
							// Setting Dialog Message
							alertDialog.setMessage("Password Mismatch. Please Re-Enter Pasword.");
							// Setting OK Button
							alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									etnewuserpass.setText("");
									etcnewuserpass.setText("");
									alertDialog.dismiss();
								}
							});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
					}
					
				}
				
			}
		});
	}
	
	public boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
	
	private class ValidateUserEmail extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Languageapp_Reset_User_Pass.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Register");
			// Set progressdialog message
			mProgressDialog.setMessage("Configure Email");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/usermanager/paswordchangechkemail.php");
				
				JSONObject json = new JSONObject();
				json.put("record1", etenteremail.getText().toString());
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {

			}
			return null;
		}
		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			if (result != null) {
				arraylist = new ArrayList<HashMap<String, String>>();
				try {
					JSONObject jsonObj = new JSONObject(result);
					jsonarray = jsonObj.getJSONArray("posts");
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject c = jsonarray.getJSONObject(i);
						String RegisterState = c.getString("RegisterState");
						if(RegisterState.equals("TRUE")){
							EmailValidate = 1;
							dmresetreqemail.setVisibility(LinearLayout.GONE);
							dmresetnewpassword.setVisibility(LinearLayout.VISIBLE);
						}
						else if(RegisterState.equals("FALSE")){
							final AlertDialog alertDialog = new AlertDialog.Builder(
									Languageapp_Reset_User_Pass.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("INVALID USER");
							// Setting Dialog Message
							alertDialog.setMessage("Please Enter Registered Email...");
							// Setting OK Button
							alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									onBackPressed();
									alertDialog.dismiss();
								}
							});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
						
						
						
					}
				}
				catch(Exception e){
					
				}
			}

		}
	}
	
	
	
	
	private class ValidateUserEmailPassword extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					Languageapp_Reset_User_Pass.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("RESET PASSWORD");
			// Set progressdialog message
			mProgressDialog.setMessage("Configure Resetting Password");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/usermanager/resetrequestedpasswords.php");
				
				JSONObject json = new JSONObject();
				json.put("record1", etenteremail.getText().toString());
				json.put("record2", etnewuserpass.getText().toString());
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {

			}
			return null;
		}
		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			final AlertDialog alertDialog = new AlertDialog.Builder(
					Languageapp_Reset_User_Pass.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("PASSWORD REST");
			// Setting Dialog Message
			alertDialog.setMessage("User Password Reset Successfully");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					onBackPressed();
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;

		}
	}
}
